<template>
  <a-modal
    v-model:visible="visible"
    :body-style="{
               height:`calc(100vh - 500px)`,
               overflowY:'auto',
               overflowX:'hidden',
           }"
    :title="$t('role.operations.auth')"
    draggable
    :width="width"
    @cancel="handleCancel"
  >
    <a-form :model="formData" ref="formRef" auto-label-width>
      <a-spin :loading="loading">
        <a-form-item label="菜单权限" field="formData.resourceIds">
          <div style="display: flex;flex-direction: column;">
            <div style="display: flex; margin-top: 5px; margin-bottom: 10px;">
              <a-checkbox
                v-model="checkExpanded"
                @change="changeExpanded"
                style="margin-right: 10px;"
              >{{ $t('role.auth.expanded') }}</a-checkbox>
              <a-checkbox
                v-model="checkStrictly"
                @change="changeStrictly"
              >{{ $t('role.auth.strictly') }}</a-checkbox>
            </div>
            <a-tree
              :field-names="{key:'id',title:'name'}"
              :checkable="true"
              :data="treeData"
              :selectable="false"
              :check-strictly="!checkStrictly"
              v-model:expanded-keys="expandedKeys"
              v-model:checked-keys="formData.resourceIds"
            />
          </div>
        </a-form-item>
      </a-spin>
    </a-form>
    <template #footer>
      <a-button
        style="margin-right: 8px"
        @click="handleCancel"
      >{{ $t('searchTable.columns.operations.close') }}</a-button>
      <a-button
        type="primary"
        @click="handleSubmit"
        :loading="loading"
      >{{ $t('searchTable.columns.operations.save') }}</a-button>
    </template>
  </a-modal>
</template>
  <script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { Modal, Message } from '@arco-design/web-vue';
import { roleResource, authResource, RoleResourceData } from '@/api/sys/role';

const { t } = useI18n();

const loading = ref(false);
const visible = ref(false);
const width = ref('calc(28%)');

const formRef = ref();
const formData = ref<RoleResourceData>({});
const changed = ref(false);

// 菜单树形结构数据
const treeData = ref<any>([]);
const expandedKeys = ref<any>([]);
// 是否展开
const checkExpanded = ref(false);
// 是否父子节点关联
const checkStrictly = ref(true);

const emit = defineEmits({ onSearch: null });

// 打开弹窗
const onOpen = async (record: any) => {
  const role = JSON.parse(JSON.stringify(record));
  if (!role || !role.id) {
    return;
  }
  visible.value = true;
  loading.value = true;
  formData.value = {
    roleId: role.id,
    resourceIds: [],
  };
  let { data } = await roleResource({ id: role.id });
  loading.value = false;
  treeData.value = data;
  deleteTreeEle(treeData.value);
  nextTick(() => {
    changed.value = false;
  });
};

// 获取菜单树
const fetchData = async (record: any) => {};

//解决渲染问题
const deleteTreeEle = (tree: any[], expanded: boolean = false) => {
  for (let i = 0; i < tree.length; i++) {
    delete tree[i].title;
    delete tree[i].icon;
    if (
      tree[i].checked == true &&
      formData.value.resourceIds.indexOf(tree[i].id) < 0
    ) {
      formData.value.resourceIds.push(tree[i].id);
    }
    if (expanded) {
      expandedKeys.value.push(tree[i].id);
    }
    if (tree[i].children && tree[i].children.length > 0) {
      deleteTreeEle(tree[i].children);
    }
  }
};

// 展开/折叠
const changeExpanded = async (value: any, e: Event) => {
  // 折叠
  if (!value) {
    expandedKeys.value = [];
    return;
  }
  deleteTreeEle(treeData.value, true);
};

// 切换父子节点关联
const changeStrictly = async (value: any, e: Event) => {
  checkStrictly.value = value;
};

// 确认
const handleSubmit = async () => {
  formRef.value.validate().then((result: any) => {
    // 校验不通过
    if (result) {
      return;
    }
    loading.value = true;
    authResource(formData.value)
      .then(() => {
        onOk();
      })
      .finally(() => {
        loading.value = false;
      });
  });
};

// 确认
const onOk = () => {
  formRef.value.clearValidate();
  formData.value = {};
  visible.value = false;
  checkExpanded.value = false;
  checkStrictly.value = true;
  expandedKeys.value = [];
  Message.success(t('operations.success'));
  emit('onSearch');
};

// 取消
const handleCancel = () => {
  if (!changed.value) {
    onCancel();
  } else {
    Modal.confirm({
      title: t('operations.cancel.title'),
      content: '',
      onOk() {
        onCancel();
      },
      onCancel() {
        visible.value = true;
      },
    });
  }
};

// 取消
const onCancel = () => {
  formRef.value.clearValidate();
  formData.value = {};
  visible.value = false;
  checkExpanded.value = false;
  checkStrictly.value = true;
  expandedKeys.value = [];
};

// 抛出函数
defineExpose({
  onOpen,
});

// 监听数据
watch(
  formData,
  (newValue, oldValue) => {
    changed.value = true;
  },
  { deep: true }
);
</script>
<style scoped lang="less">
:deep(.arco-tree-node-title-text) {
  color: black;
}
</style>
